import { useRef, useMemo, useCallback, useEffect } from 'react';
import { throttle } from 'lodash';

export default function useTooltipCarousel(maxCount, awaitTime) {
  const count = useRef(-1);
  const time = useRef(+new Date());
  const id = useRef();

  const onEvents = useMemo(
    () => ({
      mouseover: () => {
        cancelAnimationFrame(id.current);
      },
      mouseout: (params, echart) => {
        count.current = (count.current - 1) % maxCount;
        setTimeout(() => {
          handleTimer(echart);
        }, 300);
      },
    }),
    [handleTimer],
  );

  const redo = useCallback(callback => {
    const now = +new Date();
    if (now - time.current >= awaitTime) {
      time.current = now;
      callback && callback();
    }
    id.current = requestAnimationFrame(() => redo(callback));
  }, []);

  const handleReady = useCallback(
    echart => {
      setTimeout(() => {
        handleTimer(echart);
      }, 300);
      echart.getZr().on('mousemove', () => {
        cancelAnimationFrame(id.current);
      });
      const cb = throttle(() => {
        count.current = (count.current - 1) % maxCount;
        redo(() => callback(echart));
      }, 200);
      echart.getZr().on('mouseout', cb);
    },
    [handleTimer],
  );

  const callback = useCallback(echart => {
    cancelAnimationFrame(id.current);
    count.current = (count.current + 1) % maxCount;
    echart?.dispatchAction?.({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: count.current,
    });
  }, []);

  const handleTimer = useCallback(
    echart => {
      redo(() => callback(echart));
    },
    [awaitTime],
  );

  useEffect(() => () => cancelAnimationFrame(id.current), []);

  return { onEvents, handleReady };
}
